<script setup lang="ts">
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { useGetDepartmentOptions } from '@/services/module/department/useOptions'
  import { useUpdateDepartmentByCodeIds } from '@/services/pages/code/useCode'
  import { PropType, watch } from 'vue'

  const { updateForm, updateLoading, update, resetUpdateForm } = useUpdateDepartmentByCodeIds()

  const props = defineProps({
    codeIds: {
      type: Array as PropType<Array<string>>,
      required: true,
    },
    departmentIds: {
      type: Array as PropType<Array<string>>,
      default: () => [],
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  defineOptions({
    name: 'CodeUpdateDepartmentModal',
  })

  const {
    options: departmentOptions,
    getOptionsLoading: getDepartmentOptionsLoading,
    getOptions: getDepartmentOptions,
  } = useGetDepartmentOptions()

  // 弹窗显示状态
  const visible = defineModel('modelValue', { type: Boolean, default: false })

  /**
   * 隐藏弹窗
   */
  const hideDialog = () => {
    resetUpdateForm()
    visible.value = false
  }

  /**
   * 确定事件
   */
  const onConfirm = async () => {
    const res = await update()
    if (res.code === 20000) {
      HMessage.success('更新完成')
      hideDialog()
      emits('update')
      return
    }
    HMessageBox.error(res.message)
  }

  watch(visible, (value) => {
    if (value) {
      updateForm.value.codeId = props.codeIds
      getDepartmentOptions()
      if (props.departmentIds) {
        updateForm.value.departmentIds = props.departmentIds
      }
    }
  })
</script>

<template>
  <h-dialog
    v-model="visible"
    title="更改部门"
    :loading="getDepartmentOptionsLoading || updateLoading"
    :width="800"
    @close="hideDialog"
  >
    <el-form inline-message label-position="top" class="modal_form_content">
      <el-form-item label="所属部门">
        <el-select v-model="updateForm.departmentIds" placeholer="请选择所属部门" multiple>
          <el-option
            v-for="(option, optionIndex) in departmentOptions"
            :key="optionIndex"
            :label="option.name"
            :value="option.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">确定</h-button>
      <h-button is-modal @click="hideDialog">取消</h-button>
    </template>
  </h-dialog>
</template>

<style scoped lang="scss">
  :deep(.el-select__wrapper) {
    height: auto !important;
  }
</style>
